<!--
 * @Date: 2024-07-29 15:12:59
 * @Author: LiSong
 * @LastEditors: ljc
 * @LastEditTime: 2025-11-20 16:38:42
 * @Description: 预览页弹窗
-->
<template>
  <vxe-modal :="dialogAttrs1"
    :title="i18n.$st('designer.toolbar.preview')"
    :modelValue="visible"
    @close="emitClose">
    <div class="vf-render-container">
      <VFormRender ref="preForm"
        :formJson="formJson"
        :formData="formData"
        :optionData="{}"
        :busiConfig="busiConfig"
        :enumsConfig="enumsConfig"
        :designState="false"
        :previewState="true"
        @formChange="handleFormChange"
        @btnGroupLeftClick="btnGroupLeftClick"
        @btnGroupRightClick="btnGroupRightClick"
        @onTableButtonsClick="onTableButtonsClick"
        @onOperateButtonsClick="onOperateButtonsClick">
      </VFormRender>
    </div>
    <div v-if="exportFormDialogStore.visible">
      <vxe-modal :="dialogAttrs2"
        :title="exportFormDialogStore.title"
        v-model="exportFormDialogStore.visible">
        <AceCodeEditor mode="json"
          :border="true"
          :readonly="true"
          v-model="formDataJson">
        </AceCodeEditor>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary"
              :data-clipboard-text="formDataRawJson"
              @click="copyFormDataJson">
              {{exportFormDialogStore.footerBtns.btn1.text}}
            </el-button>
            <el-button @click="exportFormDialogStore.visible = false">
              {{exportFormDialogStore.footerBtns.btn3.text}}
            </el-button>
          </div>
        </template>
      </vxe-modal>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary"
          @click="getFormData">{{ i18n.$st('designer.hint.getFormData')}}</el-button>
        <el-button type="primary"
          @click="validatePreForm">表单校验</el-button>
        <el-button type="primary"
          @click="resetForm">重置表单</el-button>
        <el-button @click="emitClose">关闭</el-button>
        <!-- <el-button type="primary" @click="getFormData">{{i18n.$st('designer.hint.getFormData')}}</el-button>
        <el-button type="primary" @click="resetForm">{{i18n.$st('designer.hint.resetForm')}}</el-button>
        <el-button type="primary" @click="setFormDisabled">{{i18n.$st('designer.hint.disableForm')}}</el-button>
        <el-button type="primary" @click="setFormEnabled">{{i18n.$st('designer.hint.enableForm')}}</el-button>
        <el-button @click="visible = false">{{i18n.$st('designer.hint.closePreview')}}</el-button>
        <el-button v-if="false" @click="testLoadForm">Test Load</el-button>
        <el-button v-if="false" @click="testSetFormJson">Test SFJ</el-button>
        <el-button v-if="false" @click="testSetFormData">Test SFD</el-button>
        <el-button v-if="false" @click="testReloadOptionData">Test ROD</el-button> -->
      </div>
    </template>
  </vxe-modal>
</template>

<script setup name="FormRenderPreview">
import { reactive, ref } from 'vue';
import { i18n } from '@/utils/i18n';
import { ElMessage } from 'element-plus';
import { VfMessage } from '@/utils/vf-utils'
import {
  deepClone,
  copyToClipboard,
  generateId,
  getQueryParam,
  traverseAllWidgets,
  addWindowResizeHandler,
} from '@/utils/util';

import { AceCodeEditor } from '@/components/vf-editor'

import VFormRender from '@/components/form-render/index';

import { baseAttrs } from '@/components/dialogs/cfg/base-cofig.js'
import XEUtils from 'xe-utils';

// 表单预览弹窗
const props = defineProps({
  visible: { type: Boolean, default: false },
  formJson: { type: Object },
  formData: { type: Object },
  busiConfig: { type: Object },
  enumsConfig: { type: Object },
});

const emits = defineEmits(['close']);

const handleFormChange = (fieldName, newValue, oldValue, formModel) => {
  // console.log({fieldName, newValue, oldValue, formModel})
};

const dialogStore = reactive({
  dragClass: ['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header'],
})

const dialogAttrs1 = reactive({
  ...baseAttrs,
  height: '90%',
  width: '90%',
  className: 'vf-designer-dialog vf-preview-dialog'
})

const dialogAttrs2 = reactive({
  ...baseAttrs,
  height: '50%',
  width: '55%',
  position: {
    top: '180px'
  }
})


const exportFormDialogStore = reactive({
  title: i18n.$st('designer.hint.exportFormData'),
  visible: false,
  footerBtns: {
    btn1: {
      text: i18n.$st('designer.hint.copyFormData'),
    },
    btn2: {
      text: i18n.$st('designer.hint.saveFormData'),
    },
    btn3: {
      text: i18n.$st('designer.hint.closePreview'),
    },
  }
})

const preForm = ref();
const formDataJson = ref('');
const formDataRawJson = ref('');
const getFormData = () => {
  const formData = preForm.value.getFormData(false);
  formDataJson.value = JSON.stringify(formData, null, '  ');
  formDataRawJson.value = JSON.stringify(formData);
  exportFormDialogStore.visible = true;
};
const saveFormData = () => { };
const copyFormDataJson = e => {
  copyToClipboard(
    formDataRawJson.value,
    e,
    ElMessage,
    i18n.$st('designer.hint.copyJsonSuccess'),
    i18n.$st('designer.hint.copyJsonFail'),
  );
};
/**
 * 校验表单
 */
const validatePreForm = () => {
  preForm.value.validateForm((valid, invalidFields) => {
    // console.log(valid, invalidFields)
  });
  // validataForm()
};
/**
 * 校验表单
 */
const validataForm = () => {
  const { validateForm, getWidgetRef, getFieldWidgets, getContainerWidgets } = preForm.value;
  const fieldWidgets = getFieldWidgets();
  const containerWidgets = getContainerWidgets();
  // 获取tab容器
  let tabWidget = {};
  containerWidgets.forEach(item => {
    if (item.type === 'tab') {
      tabWidget = item;
    }
  });
  // 获取字段容器 key - value
  const fieldWidgetObj = {};
  fieldWidgets.forEach(item => {
    fieldWidgetObj[item.name] = item;
  });
  const tranfTabFields = {};
  return new Promise(resolve => {
    validateForm((valid, invalidFields) => {
      // console.log(valid, invalidFields)
      if (!valid) {
        Object.keys(invalidFields).forEach(key => {
          const tabInfo = fieldWidgetObj[key]?.tabInfo;
          let tabField = tranfTabFields[tabInfo.name];
          if (tabField) {
            tabField.fields.push(key);
          } else {
            tabField = { name: tabInfo.name, label: tabInfo.label, fields: [key] };
          }
          tranfTabFields[tabInfo.name] = tabField;
        });
        const validTabs = Object.values(tranfTabFields);
        if (validTabs && validTabs.length > 0) {
          const tabRef = getWidgetRef(tabWidget.name);
          tabRef.activeTabName = validTabs[0].name;
          VfMessage.error(`${validTabs[0].label}：请检查必填项，以及未通过校验项！`);
          resolve(false);
        } else {
          resolve(true);
        }
      } else {
        resolve(true);
      }
    });
  });
};
/**
 * 重置表单
 */
const resetForm = () => {
  preForm.value.resetForm();
};
/**
 * 关闭弹窗
 */
const emitClose = () => {
  emits('close');
};

// --------------  方法示例
const btnGroupLeftClick = (params) => {
  console.log('btnGroupLeftClick', params)
}
const btnGroupRightClick = (params) => {
  console.log('btnGroupRightClick', params)
}
const onTableButtonsClick = (...params) => {
  console.log('onTableButtonsClick', ...params)
}
const onOperateButtonsClick = (...params) => {
  console.log('onTableButtonsClick', ...XEUtils.clone(params, true))
}

</script>

<style lang="scss" scoped>
.vf-render-container {
  flex: 1;
  min-height: 100px;
  overflow: auto;
  border: 1px solid #ececec;
  padding: 8px;
  :deep(.render-form),
  :deep(.tab-container),
  :deep(.el-tabs),
  :deep(.el-tab-pane) {
    height: 100%;
  }
  // 源代码
  // :deep(.render-form > .container-wrapper) {
  //   &:only-child {
  //     height: 100%;
  //   }
  //   //   // 如果第一个元素包含display为none的el-card，可能需要特殊处理
  // }
  :deep(#alertId > .el-card) {
    height: 100%;
  }
  :deep(.render-form > .container-wrapper) {
    height: 100%;
    &:first-child {
      height: 100%;
    }
    &:not(:first-child) {
      height: auto;
    }
  }
  :deep(.el-tabs) {
    display: flex;
    flex-direction: column-reverse;
  }
  :deep(.el-tabs__header) {
    background-color: #e3f1fe;
    margin-bottom: 0;
  }
  :deep(.el-tabs__nav-scroll) {
    padding: 0 5px;
  }
  :deep(.el-tabs__content) {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0;
    padding-top: 15px;
  }
  :deep(.el-tab-pane) {
    .upload-main {
      padding: 0;
      position: relative;
      top: -15px;
    }
    // 处理插槽样式
    .slot-widget-item {
      flex: 1;
      min-height: 300px;
      .static-content-item,
      .slot-wrapper-render {
        height: 100%;
      }
    }
  }
}
</style>
<style lang="scss">
.vf-preview-dialog {
  &.vxe-modal--wrapper .vxe-modal--content {
    padding: 5px;
    display: flex;
    flex-direction: column;
  }
}
</style>
